package com.lingnan.controller;

import com.lingnan.entity.NotificationDTO;
import com.lingnan.entity.dto.*;
import com.lingnan.entity.vo.Result;
import com.lingnan.service.NotificationService;
import com.lingnan.util.NotificationUtil;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// NotificationController.java
@RestController
@RequestMapping("/notification")
@Slf4j
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class NotificationController {
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private NotificationUtil notificationUtil;
    
    /**
     * 获取用户通知列表
     */
    @GetMapping("/list")
    public Result<List<NotificationDTO>> getUserNotifications(
            @RequestParam("userId") Long userId,
            @RequestParam(value = "page",defaultValue = "1") int page,
            @RequestParam(value = "size",defaultValue = "20") int size) {
        
        List<NotificationDTO> notifications = notificationService.getUserNotifications(userId, page, size);
        return Result.ok(notifications);
    }
    
    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread-count")
    public Result<Integer> getUnreadCount(@RequestParam("userId") Long userId) {
        int count = notificationService.getUnreadCount(userId);
        return Result.ok(count);
    }
    
    /**
     * 标记通知为已读
     */
    @PostMapping("/read")
    public Result<Void> markAsRead(@RequestParam("notificationId") Long notificationId, @RequestParam("userId") Long userId) {
        notificationService.markAsRead(notificationId, userId);
        return Result.ok();
    }
    
    /**
     * 发送个人通知
     */
    @PostMapping("/send-personal")
    public Result<Void> sendPersonalNotification(
            @RequestParam("senderId") Long senderId,
            @RequestParam("receiverId") Long receiverId,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam(value = "type",defaultValue = "0") Integer type) {
        
        notificationService.sendPersonalNotification(senderId, receiverId, title, content, type);
        return Result.ok();
    }

    /**
     * 发送单个通知
     */
    @PostMapping("/send")
    public Result<Void> sendNotification(@RequestBody NotificationDTO notificationDTO) {
        try {
            notificationService.sendPersonalNotification(
                    notificationDTO.getSenderId(),
                    notificationDTO.getReceiverId(),
                    notificationDTO.getTitle(),
                    notificationDTO.getContent(),
                    notificationDTO.getType()
            );
            return Result.ok();
        } catch (Exception e) {
            log.error("发送通知失败", e);
            return Result.fail("发送通知失败");
        }
    }
    /**
     * 批量发送个人通知，消息一致
     */
    @PostMapping("/batch-send")
    public Result<Void> batchSendNotification(@RequestBody BatchNotificationDTO batchDTO) {
        try {
            notificationService.batchSendNotification(batchDTO);
            return Result.ok();
        } catch (Exception e) {
            log.error("批量发送通知失败", e);
            return Result.fail("批量发送通知失败");
        }
    }

    /**
     * 批量发送通知（通过NotificationDTO列表），消息不一致
     */
    @PostMapping("/batch-send-list")
    public Result<Void> batchSendNotification(@RequestBody List<NotificationDTO> notifications) {
        try {
            notificationService.batchSendNotification(notifications);
            return Result.ok();
        } catch (Exception e) {
            log.error("批量发送通知失败", e);
            return Result.fail("批量发送通知失败");
        }
    }
    /**
     * 发送系统公告（管理员功能）
     */
    @PostMapping("/send-announcement")
    public Result<Void> sendSystemAnnouncement(
            @RequestParam("senderId") Long senderId,
            @RequestParam("title") String title,
            @RequestParam("content") String content) {
        
        notificationService.sendSystemAnnouncement(senderId, title, content);
        return Result.ok();
    }

    /**
     * 发送简历状态通知
     */
    @PostMapping("/resume-status")
    public Result<Void> sendResumeStatusNotification(@RequestBody @Valid ResumeStatusRequest request) {
        try {
            notificationUtil.sendResumeStatusNotification(
                    request.getReceiverId(),
                    request.getCompanyName(),
                    request.getPosition(),
                    request.getStatus()
            );
            log.info("简历状态通知发送成功 - 接收者ID: {}, 公司: {}, 职位: {}, 状态: {}",
                    request.getReceiverId(), request.getCompanyName(), request.getPosition(), request.getStatus());
            return Result.ok();
        } catch (Exception e) {
            log.error("简历状态通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 发送面试邀请通知
     */
    @PostMapping("/interview-invitation")
    public Result<Void> sendInterviewInvitation(@RequestBody @Valid InterviewInvitationRequest request) {
        try {
            notificationUtil.sendInterviewInvitation(
                    request.getSenderId(),
                    request.getReceiverId(),
                    request.getCompanyName(),
                    request.getPosition(),
                    request.getInterviewTime(),
                    request.getAddress()
            );
            log.info("面试邀请通知发送成功 - 发送者ID: {}, 接收者ID: {}, 公司: {}, 职位: {}",
                    request.getSenderId(), request.getReceiverId(), request.getCompanyName(), request.getPosition());
            return Result.ok();
        } catch (Exception e) {
            log.error("面试邀请通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 发送系统维护公告
     */
    @PostMapping("/maintenance-announcement")
    public Result<Void> sendMaintenanceAnnouncement(@RequestBody @Valid MaintenanceAnnouncementRequest request) {
        try {
            notificationUtil.sendMaintenanceAnnouncement(
                    request.getAdminId(),
                    request.getMaintenanceTime(),
                    request.getDuration()
            );
            log.info("系统维护公告发送成功 - 管理员ID: {}, 维护时间: {}, 持续时间: {}",
                    request.getAdminId(), request.getMaintenanceTime(), request.getDuration());
            return Result.ok();
        } catch (Exception e) {
            log.error("系统维护公告发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 发送新职位推荐
     */
    @PostMapping("/job-recommendation")
    public Result<Void> sendJobRecommendation(@RequestBody @Valid JobRecommendationRequest request) {
        try {
            notificationUtil.sendJobRecommendation(
                    request.getReceiverId(),
                    request.getJobTitle(),
                    request.getCompanyName(),
                    request.getSalary()
            );
            log.info("职位推荐通知发送成功 - 接收者ID: {}, 职位: {}, 公司: {}, 薪资: {}",
                    request.getReceiverId(), request.getJobTitle(), request.getCompanyName(), request.getSalary());
            return Result.ok();
        } catch (Exception e) {
            log.error("职位推荐通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 发送企业认证结果通知
     */
    @PostMapping("/company-verification")
    public Result<Void> sendCompanyVerificationResult(@RequestBody @Valid CompanyVerificationRequest request) {
        try {
            notificationUtil.sendCompanyVerificationResult(
                    request.getReceiverId(),
                    request.getCompanyName(),
                    request.isApproved(),
                    request.getReason()
            );
            log.info("企业认证结果通知发送成功 - 接收者ID: {}, 公司: {}, 认证结果: {}",
                    request.getReceiverId(), request.getCompanyName(), request.isApproved() ? "通过" : "未通过");
            return Result.ok();
        } catch (Exception e) {
            log.error("企业认证结果通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 发送黑名单警告
     */
    @PostMapping("/blacklist-warning")
    public Result<Void> sendBlacklistWarning(@RequestBody @Valid BlacklistWarningRequest request) {
        try {
            notificationUtil.sendBlacklistWarning(
                    request.getReceiverId(),
                    request.getReason()
            );
            log.info("黑名单警告通知发送成功 - 接收者ID: {}, 原因: {}",
                    request.getReceiverId(), request.getReason());
            return Result.ok();
        } catch (Exception e) {
            log.error("黑名单警告通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 批量发送简历状态通知
     */
    @PostMapping("/batch/resume-status")
    public Result<Void> batchSendResumeStatusNotification(@RequestBody @Valid BatchResumeStatusRequest request) {
        try {
            int successCount = 0;
            for (ResumeStatusRequest item : request.getNotifications()) {
                try {
                    notificationUtil.sendResumeStatusNotification(
                            item.getReceiverId(),
                            item.getCompanyName(),
                            item.getPosition(),
                            item.getStatus()
                    );
                    successCount++;
                } catch (Exception e) {
                    log.error("批量发送简历状态通知失败 - 接收者ID: {}", item.getReceiverId(), e);
                }
            }
            log.info("批量简历状态通知发送完成 - 总数: {}, 成功: {}", request.getNotifications().size(), successCount);
            return Result.ok();
        } catch (Exception e) {
            log.error("批量简历状态通知发送失败", e);
            return Result.fail("批量通知发送失败: " + e.getMessage());
        }
    }

    /**
     * 通用通知发送接口（支持自定义通知内容）
     */
    @PostMapping("/custom")
    public Result<Void> sendCustomNotification(@RequestBody @Valid BatchResumeStatusRequest.CustomNotificationRequest request) {
        try {
            // 根据通知类型调用相应方法
            switch (request.getType()) {
                case "RESUME_STATUS":
                    notificationUtil.sendResumeStatusNotification(
                            request.getReceiverId(),
                            request.getCompanyName(),
                            request.getPosition(),
                            request.getStatus()
                    );
                    break;
                case "JOB_RECOMMENDATION":
                    notificationUtil.sendJobRecommendation(
                            request.getReceiverId(),
                            request.getJobTitle(),
                            request.getCompanyName(),
                            request.getSalary()
                    );
                    break;
                case "BLACKLIST_WARNING":
                    notificationUtil.sendBlacklistWarning(
                            request.getReceiverId(),
                            request.getReason()
                    );
                    break;
                default:
                    return Result.fail("不支持的通知类型: " + request.getType());
            }

            log.info("自定义通知发送成功 - 类型: {}, 接收者ID: {}", request.getType(), request.getReceiverId());
            return Result.ok();
        } catch (Exception e) {
            log.error("自定义通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }

    @PostMapping("/new-message")
    public Result<Void> sendNewMessageNotification(@RequestBody @Valid NewMessageRequest request) {
        try {
            notificationUtil.sendNewMessageNotification(
                    request.getSenderId(),
                    request.getReceiverId(),
                    request.getSenderName(),
                    request.getMessagePreview()
            );
            log.info("新聊天消息通知发送成功 - 发送者ID: {}, 接收者ID: {}, 发送者姓名: {}",
                    request.getSenderId(), request.getReceiverId(), request.getSenderName());
            return Result.ok();
        } catch (Exception e) {
            log.error("新聊天消息通知发送失败", e);
            return Result.fail("通知发送失败: " + e.getMessage());
        }
    }
}

